package com.visionvera.retrofitservice.module.base;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.WindowManager;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.visionvera.retrofitservice.R;
import com.visionvera.retrofitservice.rxbus.RxBus;
import com.visionvera.retrofitservice.rxbus.event.BaseEvent;
import com.visionvera.retrofitservice.view.EmptyLayout;
import com.visionvera.retrofitservice.view.SystemBarTintManager;

import org.reactivestreams.Subscription;

import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by dongyukun on 2017/12/7.
 */

public abstract class BaseActivity<T extends IBasePresenter>extends RxAppCompatActivity implements IBaseView, EmptyLayout.OnRetryListener, LifecycleProvider<ActivityEvent> {
    protected EmptyLayout mEmptyLayout;
    protected Context mContext;
    protected T mPresenter;

    /**
     * 绑定布局文件
     *
     * @return 布局文件ID
     */
    @LayoutRes
    protected abstract int attachLayoutRes();

    /**
     * 初始化视图控件
     */
    protected abstract void initViews();

    /**
     * 更新视图控件
     */
    protected abstract void updateViews(boolean isRefresh);

    /**
     * 处理RxBusEvent事件
     *
     * @param baseEvent
     */
    protected abstract void doRxBus(BaseEvent baseEvent);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.BaseTheme);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        setContentView(attachLayoutRes());
        mContext = this;
        registerRxBus();
        initRxBus();
        ButterKnife.bind(this);
        initViews();
        updateViews(false);
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        initTitle();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        MobclickAgent.onResume(this);//友盟统计
    }

    @Override
    protected void onPause() {
        super.onPause();
//        MobclickAgent.onPause(this);//友盟统计
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mListener.onDestroy();
        unRegisterRxBus(this);
    }

    protected void initRxBus() {
        RxBus.getInstanceBus().registerRxBus(BaseEvent.class, new Consumer<BaseEvent>() {
            @Override
            public void accept(BaseEvent baseEvent) throws Exception {
                //TODO 处理默认事件
            }
        });
    }

    private void initTitle() {
        mEmptyLayout = (EmptyLayout) findViewById(R.id.empty_layout);
//        common_title_back_iv = (ImageView) findViewById(R.id.common_title_back_iv);
//        common_title_text_tv = (TextView) findViewById(R.id.common_title_text_tv);
//        common_title_button_tv = (TextView) findViewById(R.id.common_title_button_tv);
//        common_title_pop_iv = (ImageView) findViewById(R.id.common_title_pop_iv);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        } else {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            //激活状态栏设置
            tintManager.setStatusBarTintEnabled(true);
            //设置状态栏颜色
//            tintManager.setTintResource(R.color.color_yellow);
            //激活导航栏设置
//            tintManager.setNavigationBarTintEnabled(true);
            //设置导航栏颜色
//            tintManager.setNavigationBarTintResource(R.color.color_yellow);
        }
//        if (common_title_back_iv != null) {
//            common_title_back_iv.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    onBackPressed();
//
//                }
//            });
//            common_title_back_iv.setOnTouchListener(PressEffectUtils.pressEffect());
//        }
//        if (common_title_button_tv != null) {
//            common_title_button_tv.setOnTouchListener(PressEffectUtils.pressEffect());
//        }
//        if (common_title_pop_iv != null) {
//            common_title_pop_iv.setOnTouchListener(PressEffectUtils.pressEffect());
//        }
//        setTitleBar("title");
    }

    @Override
    public void showLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_LOADING);
        }
    }

    @Override
    public void hideLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    @Override
    public void showNetError() {
        if (mEmptyLayout != null) {
            mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_NET);
            mEmptyLayout.setRetryListener(this);
        }
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void onRetry() {

    }

    /**
     * 添加 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void addFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(containerViewId, fragment);
        fragmentTransaction.commit();
    }

    /**
     * 添加 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void addFragment(int containerViewId, Fragment fragment, String tag) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        // 设置tag，不然下面 findFragmentByTag(tag)找不到
        fragmentTransaction.add(containerViewId, fragment, tag);
        fragmentTransaction.addToBackStack(tag);
        fragmentTransaction.commit();
    }

    /**
     * 替换 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void replaceFragment(int containerViewId, Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(containerViewId, fragment);
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

    /**
     * 替换 Fragment
     *
     * @param containerViewId
     * @param fragment
     */
    protected void replaceFragment(int containerViewId, Fragment fragment, String tag) {
        if (getSupportFragmentManager().findFragmentByTag(tag) == null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            // 设置tag
            fragmentTransaction.replace(containerViewId, fragment, tag);
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            // 这里要设置tag，上面也要设置tag
            fragmentTransaction.addToBackStack(tag);
            fragmentTransaction.commit();
        } else {
            // 存在则弹出在它上面的所有fragment，并显示对应fragment
            getSupportFragmentManager().popBackStack(tag, 0);
        }
    }

    /**
     * 注册rxBus
     */
    private void registerRxBus() {
        RxBus.getInstanceBus().registerRxBus(BaseEvent.class, new Consumer<BaseEvent>() {
            @Override
            public void accept(BaseEvent baseEvent) throws Exception {
                if (baseEvent != null) {
//                            if (baseEvent instanceof FinishEvent) {
//                                finish();
//                            } else {
                    doRxBus(baseEvent);
//                            }
                }
            }
        });
    }

    /**
     * 销毁rxBus
     * @param o
     */
    private void unRegisterRxBus(Object o) {
        RxBus.getInstanceBus().unSubscribe(o);
    }

    /**
     * 回调函数
     */
    public LifeCycleListener mListener;

    public void setOnLifeCycleListener(LifeCycleListener listener) {
        mListener = listener;
    }

}
